# coding: utf-8
# __author__ = "Bruce"

import hashlib
import json
import time
import urllib.request, urllib.error, urllib.parse

from django.conf import settings
from celery import shared_task

from services.datamodel.share import stats_logger


def md5(s):
    m = hashlib.md5(s.encode('utf-8'))
    return m.hexdigest()


@shared_task(ignore_result=True, queue="youmengpush")
def push_unicast(msg_array, device_token, payload):
    """
    {
        "body": {
            "ticker": "Hello World",
            "title": "你好",
            "text": "来自友盟推送",
            "after_open": "go_app"},
        "display_type": "notification"
    }
    """
    timestamp = int(time.time() * 1000)
    method = "POST"
    url = settings.YOUMEN_PUSH_URL

    for self in msg_array:
        params = {
            "appkey": self["appkey"],
            "timestamp": timestamp,
            "device_tokens": device_token,
            "type": "unicast",
            "payload": payload,
            "production_mode": "true",
        }
        post_body = json.dumps(params)
        if settings.DEBUG:
            print(post_body)
        sign = md5("%s%s%s%s" % (method, url, post_body, self["app_master"]))
        try:
            url = url + '?sign=' + sign
            data = bytes(post_body, 'utf-8')
            request = urllib.request.Request(url=url, data=data, method=method)
            r = urllib.request.urlopen(request, timeout=2)
            ret = json.loads(r.read().decode('utf-8'))
            if settings.DEBUG:
                print(ret)
            if ret["ret"].strip() != "SUCCESS":
                stats_logger.log(40, str(ret))
        except urllib.error.HTTPError as e:
            print(e.reason, e.read())
            stats_logger.log(40, str(e))
        except urllib.error.URLError as e:
            print(e.reason)
            stats_logger.log(40, str(e))
